package seatiger.tomcat.catalina.core;

import seatiger.tomcat.catalina.*;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.Enumeration;

/**
 * servlet 容器实现
 */
public class StandardWrapper extends ContainerBase implements Wrapper, ServletConfig {

    /**
     * servlet的全限定类名
     */
    private String servletClass;

    private Servlet instance;

    private StandardWrapperFacade facade = new StandardWrapperFacade(this);

    public StandardWrapper(){
        pipeline.setBasic(new StandardWrapperValve());
    }
    @Override
    public Servlet allocate() throws ServletException {
        try {
            if (instance == null){
                synchronized (this){
                    if (instance == null){
                        Loader loader = getLoader();
                        Class<?> aClass = loader.getClassLoader().loadClass(servletClass);
                        instance = (Servlet) aClass.newInstance();
                    }
                }
            }
            instance.init(facade);
            return instance;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        throw new ServletException("allocate error");
    }

    @Override
    public String getServletClass() {
        return servletClass;
    }

    @Override
    public void setServletClass(String servletClass) {
        this.servletClass = servletClass;
    }

    /**
     * wrapper的父容器只能是context
     * @param container
     */
    @Override
    public void setParent(Container container) {
        if (container != null && !(container instanceof Context)){
            throw new IllegalArgumentException(sm.getString("standardWrapper.notContext"));
        }
        super.setParent(container);
    }

    @Override
    public void addChild(Container child) {
        throw new IllegalStateException("standardWrapper.notChild");
    }

    @Override
    public void start() throws LifecycleException {
        super.start();
    }

    @Override
    public String getServletName() {
        return getName();
    }

    @Override
    public ServletContext getServletContext() {
        //通过context获取 ServletContext
        if (parent == null || !(parent instanceof Context)){
            return null;
        }
        return ((Context) parent).getServletContext();
    }

    @Override
    public String getInitParameter(String name) {
        return null;
    }

    @Override
    public Enumeration getInitParameterNames() {
        return null;
    }

    @Override
    public void stop() throws LifecycleException {
        instance = null;
        super.stop();
    }
}
